package priorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-09-10
 * Time: 17:14
 */
public class MyHeap {
    public int[] elem;
    //堆的大小
    public int useSize;

    public MyHeap() {
        elem = new int[10];
    }

    //将数组元素传入堆中
    public void initArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            elem[i] = arr[i];
            useSize++;
        }
    }

    //创建大根堆
    public void createHeap() {
        for(int parent = (useSize -1-1)/2; parent >= 0; parent--) {
            siftDown(parent,useSize);
        }
    }
    //向下调整为大根堆
    public void siftDown(int p,int useSize) {
        int cur = 2 * p + 1;
        while(cur < useSize) {
            //存在右节点，并且右节点比左节点大才会进入if语句
            if(cur+1 < useSize && elem[cur] < elem[cur+1]) {
                cur++;
            }
            //此时的cur是两个子节点的最大节点的下标
            //判断最大的子节点和父节点谁大
            if(elem[cur] > elem[p]) {
                int tmp = elem[cur];
                elem[cur] = elem[p];
                elem[p] = tmp;
                p = cur;
                cur = 2*p +1;
            }else {
                break;
            }
        }
    }
}
